﻿using Red.Controls.Shell;
using Red.Controls.ViewModels;
using Red.EngineData.View;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Red.Toolkit.AnimationViewer
{
    /// <summary>
    /// Interaction logic for AnimationListControl.xaml
    /// </summary>
    public partial class AnimationListControl : UserControl
    {
        public AnimationListControl()
        {
            InitializeComponent();
        }

        /// <summary>
        /// TODO: this will be removed and replaced by data:Interop.Path pattern, but for now we have to create tree items somehow.
        /// </summary>
        public void TempshitInitialize( DataView rootView )
        {
            DataView animationListView = rootView.GetSubView( "animations" );
            new AnimationSetListRoot( animationListView,
                item =>
                {
                    _animationList.ItemsSource = item.Children;
                    item.IsExpanded = true;
                } );

            DataView selectedObject = rootView.GetSubView( "animations.selected" );
            InteropDataItem.CreateRoot( selectedObject, item =>
                {
                    _selectedAnimationDataCategory.DataContext = item;
                } );
        }

        private void AnimationList_SelectedItemChanged( object sender, RoutedPropertyChangedEventArgs<object> e )
        {
            if ( e.NewValue != null )
            {
                AnimationSetEntryListItem selectedAnimation = e.NewValue as AnimationSetEntryListItem;
                if ( selectedAnimation != null )
                    selectedAnimation.Select();
                else
                {
                    AnimationSetListItem selectedSet = e.NewValue as AnimationSetListItem;
                    selectedSet.Select();
                }
            }
        }

        public void Refresh()
        {
            var list = _animationList.ItemsSource;
            foreach(var treeItem in list)
            {
                TreeItemEngine item = treeItem as TreeItemEngine;
                item?.FetchAndRebuild();
            }
        }

    }
}
